<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="车辆编码" prop="vehicleCode">
        <el-input
          v-model="queryParams.vehicleCode"
          clearable
          placeholder="请输入车辆编码"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆品牌" prop="vehicleName">
        <el-input
          v-model="queryParams.vehicleName"
          clearable
          placeholder="请输入车辆品牌"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="licenseNo">
        <el-input
          v-model="queryParams.licenseNo"
          clearable
          placeholder="请输入车牌号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属商户" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          clearable
          placeholder="请输入所属商户"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经营范围" prop="routeCode">
        <el-input
          v-model="queryParams.routeCode"
          clearable
          placeholder="请输入经营范围"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="自编号" prop="selfNo">
        <el-input
          v-model="queryParams.selfNo"
          clearable
          placeholder="请输入自编号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="锁标识" prop="lockFlag">
        <el-input
          v-model="queryParams.lockFlag"
          clearable
          placeholder="请输入锁标识"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vehicle:info:add']"
          icon="Plus"
          plain
          type="primary"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vehicle:info:edit']"
          :disabled="single"
          icon="Edit"
          plain
          type="success"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vehicle:info:remove']"
          :disabled="multiple"
          icon="Delete"
          plain
          type="danger"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['vehicle:info:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleAddress"
        >车辆位置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['vehicle:info:export']"
          icon="Download"
          plain
          type="warning"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="车辆编码" prop="vehicleCode" />
      <el-table-column align="center" label="车辆品牌" prop="vehicleName" />
      <el-table-column align="center" label="车牌号" prop="licenseNo" />
      <el-table-column align="center" label="车牌颜色" prop="licenseColor" />
      <el-table-column align="center" label="所属商户" prop="deptName" />
      <el-table-column align="center" label="状态" prop="status">
        <template #default="scope">
          <dict-tag :options="chelaing_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="营运编号" prop="certificateNo" />
      <el-table-column align="center" label="营运有效期" prop="certificateExpiryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.certificateExpiryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="经营范围" prop="routeCode" />
<!--      <el-table-column align="center" label="办卡日期" prop="makeCardTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.makeCardTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column align="center" label="办卡人" prop="makeCardUser" />-->
<!--      <el-table-column align="center" label="自编号" prop="selfNo" />-->
      <el-table-column align="center" label="锁标识" prop="lockFlag">
        <template #default="scope">
          <dict-tag :options="sys_notice_status" :value="scope.row.lockFlag" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="出厂日期" prop="productionDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="产品名称" align="center" prop="productionName" />-->
<!--      <el-table-column label="有效期" align="center" prop="workExpiryDate" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.workExpiryDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column align="center" label="工作状态" prop="workStatus" >
        <template #default="scope">
          <dict-tag :options="work_status" :value="scope.row.workStatus" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="电量(%)" prop="battery" />
      <el-table-column align="center" label="使用用户" prop="workUser" />
      <el-table-column align="center" label="地址" prop="address" />
<!--      <el-table-column label="部门ID" align="center" prop="deptId" />-->
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['vehicle:info:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['vehicle:info:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车辆品牌" prop="vehicleName">
          <el-input v-model="form.vehicleName" placeholder="请输入车辆品牌" />
        </el-form-item>
        <el-form-item label="车牌号" prop="licenseNo">
          <el-input v-model="form.licenseNo" placeholder="请输入车牌号" />
        </el-form-item>
<!--        <el-form-item label="车辆等级" prop="vehicleLevel">-->
<!--          <el-input v-model="form.vehicleLevel" placeholder="请输入车辆等级" />-->
<!--        </el-form-item>-->
        <el-form-item label="车牌颜色" prop="licenseColor">
          <el-input v-model="form.licenseColor" placeholder="请输入车牌颜色" />
        </el-form-item>
        <el-form-item label="所属商户" prop="deptName">
          <el-input v-model="form.deptName" placeholder="默认商户自己" />
        </el-form-item>
        <el-form-item label="营运编号" prop="certificateNo">
          <el-input v-model="form.certificateNo" placeholder="请输入营运编号" />
        </el-form-item>
        <el-form-item label="营运有效期" prop="certificateExpiryDate">
          <el-date-picker v-model="form.certificateExpiryDate"
            clearable
            placeholder="请选择营运有效期"
            type="date"
            value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="经营范围" prop="routeCode">
          <el-input v-model="form.routeCode" placeholder="请输入经营范围" />
        </el-form-item>
<!--        <el-form-item label="办卡日期" prop="makeCardTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.makeCardTime"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择办卡日期">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="办卡人" prop="makeCardUser">-->
<!--          <el-input v-model="form.makeCardUser" placeholder="请输入办卡人" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="自编号" prop="selfNo">-->
<!--          <el-input v-model="form.selfNo" placeholder="请输入自编号" />-->
<!--        </el-form-item>-->
        <el-form-item label="锁标识" prop="lockFlag">
          <el-select v-model="form.lockFlag" placeholder="请选择">
            <el-option
                v-for="dict in sys_notice_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出厂日期" prop="productionDate">
          <el-date-picker v-model="form.productionDate"
            clearable
            placeholder="请选择出厂日期"
            type="date"
            value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-form-item align="center" label="工作状态" prop="workStatus" >
          <el-select v-model="form.workStatus" placeholder="请选择">
            <el-option
                v-for="dict in work_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用用户" prop="workUser">
          <el-input v-model="form.workUser" placeholder="请输入使用用户" />
        </el-form-item>
        <el-form-item label="当前电量" prop="battery">
          <el-input v-model="form.battery" placeholder="请输入当前电量" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog v-model="isShow"  @opened="initMap" >
      <el-form class="mask">
        <div id="box">
          <div class="title">
            选择位置
          </div>
          <div class="search">
            <el-input id="search_input" v-model="searchInput" placeholder="搜索"></el-input>
            <el-button type="primary">搜索</el-button>
          </div>
          <div id="container"></div>
          <div class="sure">
            <el-button type="primary" @click="sureFn">确认</el-button>
            <el-button @click="cancelFn">取消</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>

<script  name="Info" setup>
import {addInfo, delInfo, getInfo, listInfo, updateInfo} from "@/api/vehicle/info";
import {defineEmits, onMounted, ref} from "vue"
import AMapLoader from '@amap/amap-jsapi-loader'

const emits = defineEmits(['back',"returnData"])

let map = null;
let searchInput = ref("")
// 存储标点位置
let positionArr = ref([113.392517,22.517024])
// 存储地址
let addressValue = ref("")
// 使用ref来存储Marker实例
let marker = ref(null)
let lngLatLng = ref(null)
let lngLatLat = ref(null)
let isShow = ref(false);

const { proxy } = getCurrentInstance();
const { sys_notice_status, chelaing_status, work_status } = proxy.useDict("sys_notice_status", "chelaing_status", "work_status");
const infoList = ref([]);
const open = ref(false);
const openMap = ref({});
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sureFn = ref(undefined);
const cancelFn = ref(undefined);
let geocoder = null;

const data = reactive({
  form: {
    address: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    vehicleName: null,
    licenseNo: null,
    vehicleType: null,
    motorType: null,
    vehicleLevel: null,
    licenseColor: null,
    deptName: null,
    status: null,
    certificateNo: null,
    certificateExpiryDate: null,
    routeCode: null,
    makeCardTime: null,
    makeCardUser: null,
    selfNo: null,
    lockFlag: null,
    productionDate: null,
    productionName: null,
    workExpiryDate: null,
    workStatus: null,
    workUser: null,
    res: null,
    deptId: null,
  },
  rules: {
    licenseNo: [
      { required: true, message: "车牌号不能为空", trigger: "blur" }
    ],
    vehicleType: [
      { required: true, message: "车型不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态(0启用，1禁用）不能为空", trigger: "change" }
    ],
  }
});
onMounted(() => {
  getList();
})
const { queryParams, form, rules } = toRefs(data);


function initMap(){
// 初始化配置地图
  window._AMapSecurityConfig = {
    securityJsCode: "11fa46171b5a476ff40581ce7737421d",
  };
  AMapLoader.load({
    key: "7f8922a33480e520cc450d7ffa3efb8e", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.PlaceSearch","AMap.AutoComplete","AMap.Marker","AMap.Scale","AMap.Geocoder"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
  // 异步加载插件
  .then((AMap) => {
    map = new AMap.Map("container", {
      // 设置地图容器id
      viewMode: "2D", // 地图模式
      zoom: 11, // 初始化地图级别
      center: [113.625423, 34.746652], // 初始化地图中心点位置
    });
    geocoder = new AMap.Geocoder({
      city: '郑州', // 设置城市
      radius: 1000 // 设置搜索半径
    });
    // 地图点击事件
    map.on('click',(e)=>{
      console.log(e);
      lngLatLng.value = e.lnglat.lng;
      lngLatLat.value = e.lnglat.lat;
      console.log(lngLatLng.value, lngLatLat.value);
      positionArr.value = [lngLatLng.value, lngLatLat.value]
      const address = geocoder.getAddress(e.lnglat, function(status, result) {
        if (status === 'complete') {
          console.log(result.regeocode.formattedAddress); // 输出地址信息
          return result.regeocode.formattedAddress;
        } else {
          console.log('获取地址失败');
          return '';
        }
      });
      addressValue.value = address;
      form.value.address = address;
      console.log(form.value.address)
      if (marker.value) {
        marker.value.setPosition([lngLatLng.value, lngLatLat.value]);  // 更新Marker位置
      }
    })

    let auto = new AMap.AutoComplete({
      city:"郑州市", // 限定城市，默认全国
      input:"search_input",
    })
    let placeSearch = new AMap.PlaceSearch({
      city:"郑州市",
      map:map
    });
    auto.on("select",(e)=>{
      placeSearch.search(e.poi.name)
      console.log(e.poi);
      positionArr.value = [e.poi.location.lng,e.poi.location.lat]
      addressValue.value = e.poi.address
      if (marker.value) {
        marker.value.setPosition([e.poi.location.lng,e.poi.location.lat]);  // 更新Marker位置
      }
    })
    // 标点位置
    marker.value = new AMap.Marker({
      position: [113.625423, 34.746652], //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      map: map, // 当操作完成时，应该将结果展示在哪个地图上
    })
    map.add(marker)


    sureFn.value = ()=>{
      isShow.value = false
      emits('back',isShow.value)
      emits('returnData', {
        positionArr: positionArr.value,
        addressValue: addressValue.value
      });
      form.value.address = addressValue.value;
      form.value.point = positionArr.value[0]+","+positionArr.value[1];
      updateVehicle();
    }

    cancelFn.value = ()=>{
      isShow.value = false
      emits('back',isShow.value)
    }
  })
  .catch((e) => {
    console.log(e);
  });
}

function handleAddress(row){
  isShow.value = true;
  const _vehicleCode = row.vehicleCode || ids.value
  getInfo(_vehicleCode).then(response => {
    form.value = response.data;
  });
}
/** 提交按钮 */
function updateVehicle() {
  if (form.value.vehicleCode != null) {
    updateInfo(form.value).then(response => {
      proxy.$modal.msgSuccess("更新位置成功");
      open.value = false;
      getList();
    });
  }
}
  /** 查询车辆信息列表 */
  function getList() {
    loading.value = true;
    listInfo(queryParams.value).then(response => {
      infoList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

// 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

// 表单重置
  function reset() {
    form.value = {
      vehicleCode: null,
      vehicleName: null,
      licenseNo: null,
      vehicleType: null,
      motorType: null,
      vehicleLevel: null,
      licenseColor: null,
      deptName: null,
      status: null,
      certificateNo: null,
      certificateExpiryDate: null,
      routeCode: null,
      makeCardTime: null,
      makeCardUser: null,
      selfNo: null,
      lockFlag: null,
      productionDate: null,
      productionName: null,
      workExpiryDate: null,
      workStatus: null,
      workUser: null,
      res: null,
      deptId: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      remark: null
    };
    proxy.resetForm("infoRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

// 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.vehicleCode);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加车辆信息";
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _vehicleCode = row.vehicleCode || ids.value
    getInfo(_vehicleCode).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改车辆信息";
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["infoRef"].validate(valid => {
      if (valid) {
        if (form.value.vehicleCode != null) {
          updateInfo(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addInfo(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _vehicleCodes = row.vehicleCode || ids.value;
    proxy.$modal.confirm('是否确认删除车辆信息编号为"' + _vehicleCodes + '"的数据项？').then(function () {
      return delInfo(_vehicleCodes);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    });
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('vehicle/info/export', {
      ...queryParams.value
    }, `info_${new Date().getTime()}.xlsx`)
  }

</script>
<style scoped>
.mask {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,.6);
}

#container {
  border-radius: 10px;
  padding:0;
  margin: 0;
  width: 100%;
  height: 100%;
}

.title {
  width: 100%;
  text-align: left;
  margin-bottom: 20px;
}

.search {
  width: 100%;
  height: 30px;
  display: flex;
  margin-bottom: 20px;
}

.search .el-input {
  width: 100%;
  height: 30px;
  border-radius: 5px;
}

.search :deep(.el-input__wrapper) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.search .el-button {
  height: 100%;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: none;
}

#box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 50%;
  height: 80%;
  margin: 0 auto;
  background-color: #ffffff;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
  padding: 1.5vw;
}

.sure {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  width: 100%;
}
</style>